package com.cynteka.cyfoman.core.collection.command;

import com.cynteka.cyfoman.core.Util;
import org.apache.commons.chain.Catalog;
import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
import org.apache.commons.chain.impl.ContextBase;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import java.util.Map;

/**
 * User: Sergey
 * Date: 10.08.11
 * Time: 13:57
 */
public class TransformCommand implements Command, BeanFactoryAware {
    private BeanFactory beanFactory;

    public Map getContext() {
        return context;
    }

    public void setContext(Map context) {
        this.context = context;
    }

    private Map context;

    public String getNewCommandId() {
        return newCommandId;
    }

    public void setNewCommandId(String newCommandId) {
        this.newCommandId = newCommandId;
    }

    private String newCommandId;

    public Catalog getCatalog() {
        return catalog;
    }

    public void setCatalog(Catalog catalog) {
        this.catalog = catalog;
    }

    private Catalog catalog;

    @Override
    public boolean execute(Context context) throws Exception {
        if(catalog == null)
            catalog = Util.getCatalog(beanFactory);

        Command newCmd = catalog.getCommand(newCommandId);
        if(newCmd != null) {
            ContextBase newCtx = new ContextBase();
            newCtx.putAll(context);
            newCtx.putAll(this.context);

            newCmd.execute(newCtx);
        }
        return false;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
